package com.yanqu.road.server.manger.banquet;

import com.yanqu.road.dao.impl.cross.banquet.CrossBanquetMemberNotPoolDaoImpl;
import com.yanqu.road.dao.impl.servercenter.CrossServerInfoDaoImpl;
import com.yanqu.road.entity.DataStatus;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.banquet.BanquetGiftInfo;
import com.yanqu.road.entity.banquet.BanquetInfo;
import com.yanqu.road.entity.banquet.UserCrossBanquetData;
import com.yanqu.road.entity.banquet.baifubanquet.GoodBanquetFinishReceiveData;
import com.yanqu.road.entity.banquet.cross.CrossBanquetMember;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.log.LogBanquetIntegral;
import com.yanqu.road.entity.player.PlayerState;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.servercenter.CrossServerInfo;
import com.yanqu.road.entity.servercenter.DbInfo;
import com.yanqu.road.entity.servercenter.TitleInfo;
import com.yanqu.road.entity.task.args.union.UnionActivityTaskArgs;
import com.yanqu.road.logic.bussiness.DaoHelper;
import com.yanqu.road.logic.bussiness.player.UserBanquetBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.logic.thread.ThreadTaskManger;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.banquet.BanquetProto;
import com.yanqu.road.pb.banquet.CrossBanquetProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.banquet.BanquetModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.AttributeModule;
import com.yanqu.road.server.gameplayer.module.player.BeautyModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.xiaomian.XiaoMianModule;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.manger.MultipleLanguageMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.config.TitleMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.WorldMessageMgr;
import com.yanqu.road.server.manger.rank.RankMgr;
import com.yanqu.road.server.pb.BanquetPb;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.server.timer.banquet.CrossBanquetSyncMemberTask;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

import static com.yanqu.road.server.manger.banquet.BanquetMgr.isBanquetType;

/**
 * 宴会
 */
public class CrossBanquetMgr extends TempMgr {

    private static Map<String, UserCrossBanquetData> userCrossBanquetDataMap = new ConcurrentHashMap<>();

    private static Map<String, Map<Long, CrossBanquetMember>> crossBanquetMemberMap = new ConcurrentHashMap<>();

    private static Map<String, Object> lockMap;

    private static RandomHelper random = new RandomHelper();

    private static ThreadTaskManger threadTaskManger;

    private static AtomicInteger taskId = new AtomicInteger(1);

    /**
     * 待领取的百福宴会奖励 k:玩家id
     */
    private static Map<Long, List<GoodBanquetFinishReceiveData>> finishGoodBanquetMap = new ConcurrentHashMap<>();

    /**
     * 在活动里玩家id
     */
    private static Set<Long> inSystemUserSet = Collections.synchronizedSet(new HashSet<>());

    private static Map<Long, UserBaseInfo> userBaseInfoMap = new ConcurrentHashMap<>();

    public static int getBanquetMemberCount(String banquetId) {
        if(!userCrossBanquetDataMap.containsKey(banquetId)){
            return 0;
        }
        return userCrossBanquetDataMap.get(banquetId).getUserCount();
    }

    //用户移除场景
    public static int removeBanquetScene(long userId,String banquetId){
        Object lockObject = getLockValue(banquetId);
        if(lockObject == null){
            return GameErrorCode.E_GAME_ERROR;
        }
        synchronized (lockObject){
            if(userCrossBanquetDataMap.get(banquetId) != null){
                userCrossBanquetDataMap.get(banquetId).removeSceneUser(userId);
            }
        }
        return 0;
    }

    //获取开启的宴会,优先将要结束的下发下去
    public static Map<String, UserCrossBanquetData> getBanquetOpen(GamePlayer player){
        int count = 0;
        Map<String, UserCrossBanquetData> banquetMap = new ConcurrentHashMap<>();
        List<UserCrossBanquetData> banquetList = new ArrayList<>(userCrossBanquetDataMap.values());
        banquetList.sort(new BanquetSort());
        for(UserCrossBanquetData data : banquetList){
            if(!isBanquetOver(data.getBanquetId()) && data.getUserId() != player.getUserId()){
                banquetMap.put(data.getBanquetId(),data);
                count++;
            }
            if(count >= GameConfig.BANQUET_LIST_MAX){
                break;
            }
        }
        return banquetMap;
    }

    public static Map<String, UserCrossBanquetData> getBanquetOpen(){
        Map<String, UserCrossBanquetData> banquetMap = new ConcurrentHashMap<>();
        for(UserCrossBanquetData data : userCrossBanquetDataMap.values()){
            if(!isBanquetOver(data.getBanquetId())){
                banquetMap.put(data.getBanquetId(),data);
            }
        }
        return banquetMap;
    }

    public static Map<String, UserCrossBanquetData> getBanquetOpen(int banquetType){
        Map<String, UserCrossBanquetData> banquetMap = new ConcurrentHashMap<>();
        for(UserCrossBanquetData data : userCrossBanquetDataMap.values()){
            if(banquetType == eBanquetType.CrossBanquet.getValue()){
                if(!isBanquetOver(data.getBanquetId()) && BanquetConfigMgr.isCrossBanquet(data.getType())){
                    banquetMap.put(data.getBanquetId(),data);
                }
            }else if(banquetType == eBanquetType.CrossUserBanquet.getValue()){
                if(!isBanquetOver(data.getBanquetId()) && BanquetConfigMgr.isCrossUserBanquet(data.getType())){
                    banquetMap.put(data.getBanquetId(),data);
                }
            }
        }
        return banquetMap;
    }

    public static Map<String, UserCrossBanquetData> getBanquetOpen(GamePlayer player,int banquetType){
        Map<String, UserCrossBanquetData> banquetMap = new ConcurrentHashMap<>();
        for(UserCrossBanquetData data : userCrossBanquetDataMap.values()){
            if(banquetType == eBanquetType.CrossBanquet.getValue() && data.getUserId() != player.getUserId()){
                if(!isBanquetOver(data.getBanquetId()) && BanquetConfigMgr.isCrossBanquet(data.getType())){
                    banquetMap.put(data.getBanquetId(),data);
                }
            }else if(banquetType == eBanquetType.CrossUserBanquet.getValue() && data.getUserId() != player.getUserId()){
                if(!isBanquetOver(data.getBanquetId()) && BanquetConfigMgr.isCrossUserBanquet(data.getType())){
                    banquetMap.put(data.getBanquetId(),data);
                }
            }
        }
        return banquetMap;
    }

    public static int getRewardCrossBanquet(GamePlayer player, CrossBanquetProto.CrossBanquetGetRewardResp reqMsg) {
        for(BanquetProto.BanquetGetRewardTempMsg temp : reqMsg.getRewardListList()){
            long popularity = temp.getPopularity();
            long integral = temp.getIntegral();
            String endRewardStr = temp.getReward();

            CrossBanquetMgr.addBanquetPopularityAndIntegral(player,popularity,integral,eLogMoneyType.BanquetOpenEndReward.getValue());
            //宴会结束后的奖励
            Property endReward = PropertyHelper.parseStringToProperty(endRewardStr);
            player.getModule(CurrencyModule.class).addCurrency(endReward,eLogMoneyType.Banquet,eLogMoneyType.BanquetOpenEndReward);


            //可能手动领取的，也要更新
            UserCrossBanquetData banquetData = getBanquet(temp.getBanquetId());
            if(reqMsg.getAutoOpen() || (banquetData != null && banquetData.getAutoOpen() == 1)){
                CrossBanquetAutoOpenMgr.updateAutoRewardSuccess(player, temp, popularity, integral);
            }
        }
        return 0;
    }

    public static void enterNextBanquet(GamePlayer player, String curBanquetId, int pageNum, int pageSize) {
        long userId = player.getUserId();
        UserCrossBanquetData nextBanquet = null;
        Map<String, UserCrossBanquetData> dataMap = getCrossFeastBanquet();
        for (UserCrossBanquetData data : dataMap.values()) {
            String banquetId = data.getBanquetId();
            if (Objects.equals(banquetId, curBanquetId)) {
                continue;
            }
            Map<Long, CrossBanquetMember> memberMap = crossBanquetMemberMap.get(banquetId);
            if (memberMap == null || !memberMap.containsKey(userId)) {
                nextBanquet = data;
                break;
            }
        }
        CrossBanquetProto.BanquetEnterNextResp.Builder resp = CrossBanquetProto.BanquetEnterNextResp.newBuilder();
        if (nextBanquet == null) {
            resp.setRet(GameErrorCode.E_BANQUET_NO_NEXT);
        }else {
            resp.setRet(0);
            resp.setCount(nextBanquet.getUserCount());
            BanquetProto.BanquetTemp.Builder banquetDataTempMsg = BanquetPb.parseBanquetDataTempMsgCross(player, nextBanquet);
            resp.setBanquetInfo(banquetDataTempMsg);
            Map<Long, CrossBanquetMember> userBanquetMemberMap = getBanquetMemberMap(nextBanquet.getBanquetId(), pageSize, pageNum);
            for (CrossBanquetMember member : userBanquetMemberMap.values()) {
                resp.addMemberList(BanquetPb.parseBanquetMemberTempMsg(member));
            }
        }
        player.sendPacket(ClientProtocol.U_BANQUET_CROSU_ENTER_NEXT,resp);

    }

    private static Map<String, UserCrossBanquetData> getCrossFeastBanquet() {
        Map<String, UserCrossBanquetData> resMap = new ConcurrentHashMap<>();
        List<UserCrossBanquetData> banquetList = new ArrayList<>(userCrossBanquetDataMap.values());
        for(UserCrossBanquetData info : banquetList){
            if(!isBanquetOver(info.getBanquetId()) && (BanquetConfigMgr.isCrossBanquet(info.getType()) || BanquetConfigMgr.isCrossMogulBirthdayBanquet(info.getType()))){
                resMap.put(info.getBanquetId(),info);
            }
        }
        return resMap;
    }

    //宴会按照结束时间从小到大排序
    static class BanquetSort implements Comparator<UserCrossBanquetData> {
        @Override
        public int compare(UserCrossBanquetData o1, UserCrossBanquetData o2) {
            if (o1.getOverTime() == o2.getOverTime()) {
                return 0;
            }
            if (o1.getOverTime() >= o2.getOverTime()) {
                return 1;
            }
            return -1;
        }
    }

    //同步剩下的宴会成员给客户端
    public static void syncCrossBanquetMemberTask(long userId, String banquetId, int sendTime, int memNum, int page){
        if (threadTaskManger != null) {
            threadTaskManger.addTask(taskId.getAndIncrement(),new CrossBanquetSyncMemberTask(userId, banquetId, sendTime, memNum, page));
        }
    }

    public static boolean isBanquetOver(String banquetId){
        UserCrossBanquetData userCrossBanquetData = userCrossBanquetDataMap.get(banquetId);
        if(userCrossBanquetData == null){
            return true;
        }
        if(userCrossBanquetData.getOverTime() < System.currentTimeMillis()){
            return true;
        }
        BanquetInfo banquetInfo = BanquetConfigMgr.getBanquetInfo(userCrossBanquetData.getType());
        if(banquetInfo == null){
            return true;
        }
        if(banquetInfo.getSeat() != 0 && userCrossBanquetData.getUserCount() >= banquetInfo.getSeat()){
            return true;
        }
        return false;
    }

    //判断是不是已经开启活动了
    private static boolean canOpenBanquet(long userId){
        List<UserCrossBanquetData> banquetList = new ArrayList<>(userCrossBanquetDataMap.values());
        for(UserCrossBanquetData data : banquetList){
            if(!isBanquetOver(data.getBanquetId()) && data.getUserId() == userId && data.getStatus() == 1){
                return false;
            }
        }
        return true;
    }

    //原本只有一种跨服类型，现在改成两个了要判断类型了
    public static boolean canOpenBanquet(long userId,int type){
        List<UserCrossBanquetData> banquetList = new ArrayList<>(userCrossBanquetDataMap.values());
        for(UserCrossBanquetData data : banquetList){
            if(!isBanquetOver(data.getBanquetId()) && data.getUserId() == userId && data.getStatus() == 1 && BanquetConfigMgr.isTheSameType(data.getType(),type)){
                return false;
            }
        }
        return true;
    }

    //判断是不是同一个活动(有可能同步失败再次同步)
    private static boolean hasSameBanquet(long userId,String banquetId){
        List<UserCrossBanquetData> banquetList = new ArrayList<>(userCrossBanquetDataMap.values());
        for(UserCrossBanquetData data : banquetList){
            if(!isBanquetOver(data.getBanquetId()) && data.getUserId() == userId && data.getStatus() == 0 && data.getBanquetId().equals(banquetId)){
                return true;
            }
        }
        return false;
    }



    //开启宴会跨服通知可以开启
    public static int openCrossBanquet(GamePlayer player,String banquetId,String invitationId,int type,String serverIdList,String giftTypeAccept, boolean autoOpen){
        BanquetInfo banquetInfo = BanquetConfigMgr.getBanquetInfo(type);
        if(banquetInfo == null){
            return GameErrorCode.E_BANQUET_INFO_ERROR;
        }
        if(!canOpenBanquet(player.getUserId(),banquetInfo.getId())){
            return GameErrorCode.E_BANQUET_ONLY_ONE;
        }

        if(hasSameBanquet(player.getUserId(),banquetId)){
            CrossBanquetProto.OpenCrossBanquetReq.Builder msg = CrossBanquetProto.OpenCrossBanquetReq.newBuilder();
            msg.setBanquetId(banquetId);
            msg.setAutoOpen(autoOpen);

            TitleInfo titleInfo = TitleMgr.getTitleInfo(player.getTitleId());
            //头衔加成
            int titleAdd = titleInfo.getBanquetEffect();
            //门客技能加成
            int skillAdd = BanquetMgr.getBanquetJoinSkillAddition(player);
            msg.setTitleAdd(titleAdd);
            msg.setPatronsSkillAdd(skillAdd);
            msg.setPlayerBaseData(PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.getUserBaseInfo(player.getUserId(), GameServer.getInstance().getServerId())));
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_OPEN_BANQUET, msg);
            GamePlayerMgr.sendPacket(player.getUserId(), pbMsg);
            return 0;
        }

        String invitationInfo = "";
        if(BanquetConfigMgr.isCrossBanquet(type) || BanquetConfigMgr.isCrossMogulBirthdayBanquet(type)){
            BanquetModule banquetModule = player.getModule(BanquetModule.class);
            if(!banquetModule.checkUserInvitation(invitationId,type)){
                return GameErrorCode.E_BANQUET_INVITATION;
            }else{
                invitationInfo = banquetModule.useUserInvitation(invitationId,type);
            }
        }else if(BanquetConfigMgr.isCrossUserBanquet(type)){
            //跨服宴会没有道具消耗，只要用帖子就可以了，不然会爆炸
            if(!"0".equals(banquetInfo.getOpenConsume()) && !autoOpen){
                if(!player.getModule(CurrencyModule.class).removeCurrency(PropertyHelper.parseStringToProperty(banquetInfo.getOpenConsume()),
                        eLogMoneyType.Banquet,eLogMoneyType.BanquetOpenConsume)){
                    return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
                }
            }
        }else{
            return GameErrorCode.E_BANQUET_INFO_ERROR;
        }

        UserCrossBanquetData userCrossBanquetData = new UserCrossBanquetData();
        userCrossBanquetData.setBanquetId(banquetId);
        UserInfo userInfo = player.getUserInfo();
        userCrossBanquetData.setServerId((int)GameServer.getInstance().getServerId());
        userCrossBanquetData.setUserId(userInfo.getUserId());
        userCrossBanquetData.setOpenTime(System.currentTimeMillis());
        userCrossBanquetData.setOverTime(System.currentTimeMillis() + banquetInfo.getBanquetTime()*1000);
        userCrossBanquetData.setSendReward(false);
        userCrossBanquetData.setType(type);
        userCrossBanquetData.setPopularity(0);
        userCrossBanquetData.setIntegral(0);
        userCrossBanquetData.setUserCount(0);
        userCrossBanquetData.setUserBaseInfo(UserMgr.parseUserBaseInfo(userInfo,GameServer.getInstance().getServerId()));
        userCrossBanquetData.setStatus(0);
        userCrossBanquetData.setServerListStr(serverIdList);
        userCrossBanquetData.setInvitationId(invitationId);
        userCrossBanquetData.setInvitationInfo(invitationInfo);
        userCrossBanquetData.setGiftTypeAccept(giftTypeAccept);
        userCrossBanquetData.setAutoOpen(autoOpen ? 1 : 0);
        userCrossBanquetData.setInsertOption();

        userCrossBanquetDataMap.put(userCrossBanquetData.getBanquetId(),userCrossBanquetData);
        crossBanquetMemberMap.put(userCrossBanquetData.getBanquetId(),new ConcurrentHashMap<>());
        addLockValue(banquetId);

        CrossBanquetProto.OpenCrossBanquetReq.Builder msg = CrossBanquetProto.OpenCrossBanquetReq.newBuilder();
        msg.setBanquetId(banquetId);
        msg.setAutoOpen(autoOpen);
        TitleInfo titleInfo = TitleMgr.getTitleInfo(player.getTitleId());
        //头衔加成
        int titleAdd = titleInfo.getBanquetEffect();
        //门客技能加成
        int skillAdd = BanquetMgr.getBanquetJoinSkillAddition(player);
        msg.setTitleAdd(titleAdd);
        msg.setPatronsSkillAdd(skillAdd);
        msg.setPlayerBaseData(PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.getUserBaseInfo(player.getUserId(), GameServer.getInstance().getServerId())));
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_OPEN_BANQUET, msg);
        GamePlayerMgr.sendPacket(player.getUserId(), pbMsg);

        return 0;
    }

    public static void syncCrossBanquet(GamePlayer player) {
        player.sendPacket(Protocol.U_BANQUET_CROSS_SYNC, BanquetPb.parseCrossBanquetListSyncMsg(player, getCrossBanquet()));
    }

    /**
     * 获取玩家可以赴百福宴的集合中，结束时间最长的宴会结束时间 （红点需要）
     * @param player
     */
    public static void syncCrossGoodBanquet(GamePlayer player) {
        ActivityInfo activityInfo = CrossBanquetMgr.getEnterGoodBanquetActivityInfo();
        if (activityInfo != null) {
            CrossBanquetProto.GoodBanquetGetOpenTimeCrossReqMsg.Builder builder = CrossBanquetProto.GoodBanquetGetOpenTimeCrossReqMsg.newBuilder();
            builder.setActivityId(activityInfo.getActivityId());
            player.sendPacket(CrossProtocol.C2_GOOD_BANQUET_GET_OPEN_TIME, builder);

        }
    }

    //获取盛宴的宴会，用于同步和登录下发
    public static Map<String,UserCrossBanquetData> getCrossBanquet(){
        Map<String, UserCrossBanquetData> resMap = new ConcurrentHashMap<>();
        List<UserCrossBanquetData> banquetList = new ArrayList<>(userCrossBanquetDataMap.values());
        for(UserCrossBanquetData info : banquetList){
            if(!isBanquetOver(info.getBanquetId())){
                resMap.put(info.getBanquetId(),info);
            }
        }
        return resMap;
    }

    public static UserCrossBanquetData getUserBanquet(long userId){
        List<UserCrossBanquetData> userCrossBanquetDataList = new ArrayList<>(userCrossBanquetDataMap.values());
        for(UserCrossBanquetData data : userCrossBanquetDataList){
            if(!isBanquetOver(data.getBanquetId()) && data.getUserId() == userId && isBanquetType(data.getType(),eBanquetType.CrossUserBanquet.getValue())){
                return data;
            }
        }
        return null;
    }

    public static boolean isSelfJoin(long selfUserId, String banquetId) {
        if (crossBanquetMemberMap.containsKey(banquetId) && crossBanquetMemberMap.get(banquetId).containsKey(selfUserId)) {
            return true;
        }
        return false;
    }

    //开启宴会后跨服第二次返回
    public static int successCrossBanquet(GamePlayer player,String banquetId,long openTime,long overTime, boolean autoOpen){
        Object lockObject = getLockValue(banquetId);
        if(lockObject != null){
            synchronized (lockObject){
                UserCrossBanquetData userCrossBanquetData = userCrossBanquetDataMap.get(banquetId);
                userCrossBanquetData.setOpenTime(openTime);
                userCrossBanquetData.setOverTime(overTime);
                userCrossBanquetData.setStatus(1);
                syncSelfCrossBanquet(player,null);
                syncBanquetClient(player,userCrossBanquetData);
            }

            //更新自动开宴会记录
            if(autoOpen){
                UserCrossBanquetData userCrossBanquetData = userCrossBanquetDataMap.get(banquetId);
                CrossBanquetAutoOpenMgr.updateAutoOpenSuccess(player.getUserId(), banquetId, openTime, overTime, userCrossBanquetData.getType());
            }
        }
        return 0;
    }

    //同步开启的宴会，也是同步宴会信息的
    public static void syncBanquetSystem(GamePlayer player,CrossBanquetProto.SyncCrossBanquetTemp temp) {
        Object lockObject = getLockValue(temp.getBanquetId());
        UserCrossBanquetData userCrossBanquetData = new UserCrossBanquetData();
        if(lockObject == null){
            userCrossBanquetData.setBanquetId(temp.getBanquetId());
            userCrossBanquetData.setServerId(temp.getServerId());
            userCrossBanquetData.setInvitationId(temp.getInvitationId());
            userCrossBanquetData.setInvitationInfo(temp.getInvitationInfo());
            userCrossBanquetData.setUserId(temp.getUserId());
            userCrossBanquetData.setOpenTime(temp.getOpenTime());//用这个来同步和跨服的同步开启
            userCrossBanquetData.setOverTime(temp.getOverTime());
            userCrossBanquetData.setSendReward(temp.getIsSendReward());
            userCrossBanquetData.setType(temp.getType());
            userCrossBanquetData.setPopularity(temp.getPopularity());
            userCrossBanquetData.setIntegral(temp.getIntegral());
            userCrossBanquetData.setUserCount(temp.getUserCount());
            userCrossBanquetData.setUserBaseInfo(PlayerBasePb.parseBaseUserInfo(temp.getUserBaseInfo()));
            userCrossBanquetData.setStatus(temp.getStatus());
            userCrossBanquetData.setServerListStr(temp.getServerList());
            userCrossBanquetData.setGiftTypeAccept(temp.getGiftTypeAccept());
            userCrossBanquetData.setMessage(temp.getMessage());
            userCrossBanquetData.setInsertOption();

            userCrossBanquetDataMap.put(userCrossBanquetData.getBanquetId(),userCrossBanquetData);
            if(!crossBanquetMemberMap.containsKey(userCrossBanquetData.getBanquetId())){
                crossBanquetMemberMap.put(userCrossBanquetData.getBanquetId(),new ConcurrentHashMap<>());
            }
            addLockValue(temp.getBanquetId());
        }else{
            synchronized (lockObject){
                userCrossBanquetData = userCrossBanquetDataMap.get(temp.getBanquetId());
                userCrossBanquetData.setPopularity(temp.getPopularity());
                userCrossBanquetData.setIntegral(temp.getIntegral());
                userCrossBanquetData.setUserCount(temp.getUserCount());
                userCrossBanquetData.setSendReward(temp.getIsSendReward());
                userCrossBanquetData.setGiftTypeAccept(temp.getGiftTypeAccept());
                userCrossBanquetData.setMessage(temp.getMessage());
            }
        }
    }

    public static void syncBanquet(GamePlayer player,CrossBanquetProto.SyncCrossBanquetTemp temp) {
        Object lockObject = getLockValue(temp.getBanquetId());
        UserCrossBanquetData userCrossBanquetData = new UserCrossBanquetData();
        if(lockObject == null){
            userCrossBanquetData.setBanquetId(temp.getBanquetId());
            userCrossBanquetData.setServerId(temp.getServerId());
            userCrossBanquetData.setInvitationId(temp.getInvitationId());
            userCrossBanquetData.setInvitationInfo(temp.getInvitationInfo());
            userCrossBanquetData.setUserId(temp.getUserId());
            userCrossBanquetData.setOpenTime(temp.getOpenTime());//用这个来同步和跨服的同步开启
            userCrossBanquetData.setOverTime(temp.getOverTime());
            userCrossBanquetData.setSendReward(temp.getIsSendReward());
            userCrossBanquetData.setType(temp.getType());
            userCrossBanquetData.setPopularity(temp.getPopularity());
            userCrossBanquetData.setIntegral(temp.getIntegral());
            userCrossBanquetData.setUserCount(temp.getUserCount());
            userCrossBanquetData.setUserBaseInfo(PlayerBasePb.parseBaseUserInfo(temp.getUserBaseInfo()));
            userCrossBanquetData.setStatus(temp.getStatus());
            userCrossBanquetData.setServerListStr(temp.getServerList());
            userCrossBanquetData.setGiftTypeAccept(temp.getGiftTypeAccept());
            userCrossBanquetData.setMessage(temp.getMessage());
            userCrossBanquetData.setInsertOption();

            userCrossBanquetDataMap.put(userCrossBanquetData.getBanquetId(),userCrossBanquetData);
            if(!crossBanquetMemberMap.containsKey(userCrossBanquetData.getBanquetId())){
                crossBanquetMemberMap.put(userCrossBanquetData.getBanquetId(),new ConcurrentHashMap<>());
            }
            addLockValue(temp.getBanquetId());
            syncBanquetClient(player,userCrossBanquetData);
        }else{
            synchronized (lockObject){
                userCrossBanquetData = userCrossBanquetDataMap.get(temp.getBanquetId());
                if(temp.getUserCount() >= userCrossBanquetData.getUserCount()) {
                    userCrossBanquetData.setPopularity(temp.getPopularity());
                    userCrossBanquetData.setIntegral(temp.getIntegral());
                    userCrossBanquetData.setUserCount(temp.getUserCount());
                    userCrossBanquetData.setSendReward(temp.getIsSendReward());
                    userCrossBanquetData.setGiftTypeAccept(temp.getGiftTypeAccept());
                    userCrossBanquetData.setMessage(temp.getMessage());
                }
            }
        }
    }

    public static void syncBanquetClient(GamePlayer player,UserCrossBanquetData userCrossBanquetData) {
        UserBaseInfo userBaseInfo = userCrossBanquetData.getUserBaseInfo();
        WorldMessageMgr.worldNotify(userCrossBanquetData.getUserId(),userCrossBanquetData.getUserBaseInfo(), eMessageType.BanquetOpenNotice.getValue(), userBaseInfo.getCity(), userBaseInfo.getTitleId(),
                userBaseInfo.getNickName(), userCrossBanquetData.getType(),userCrossBanquetData.getBanquetId());

        if(BanquetConfigMgr.isCrossBanquet(userCrossBanquetData.getType()) || BanquetConfigMgr.isCrossMogulBirthdayBanquet(userCrossBanquetData.getType())){
            List<GamePlayer> playerList = GamePlayerMgr.getCopyPlayerList();
            for(GamePlayer player1 : playerList){
                syncCrossBanquet(player1);
            }
        }
    }

    //人气礼同步
    private static void popRewardSync(UserCrossBanquetData banquetData){
        if(BanquetConfigMgr.isSendCrossBanquetPopRewardPoint(banquetData.getUserCount())){
            List<Long> playerIdList = GamePlayerMgr.getAllOnlinePlayerId();
            for(Long userId : playerIdList){
                GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
                player.getModule(BanquetModule.class).crossBanquetPopRewardSync(banquetData);
            }
        }
    }

    //生成给跨服的pb，头衔加成和门客技能加成
    public static CrossBanquetProto.JoinCrossBanquetReq.Builder joinBanquetMsg(GamePlayer player,String banquetId,int giftId) {
        CrossBanquetProto.JoinCrossBanquetReq.Builder msg = CrossBanquetProto.JoinCrossBanquetReq.newBuilder();
        TitleInfo titleInfo = TitleMgr.getTitleInfo(player.getTitleId());
        //头衔加成
        int titleAdd = titleInfo.getBanquetEffect();
        //门客技能加成
        int skillAdd = BanquetMgr.getBanquetJoinSkillAddition(player);
        msg.setBanquetId(banquetId);
        msg.setGiftId(giftId);
        msg.setTitleAdd(titleAdd);
        msg.setPatronsSkillAdd(skillAdd);
        msg.setPlayerBaseData(PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.parseUserBaseInfo(player.getUserInfo(), GameServer.getInstance().getServerId())));
        ActivityInfo crbAcInfo = NormalActivityMgr.getRunningCrossBanquetRankActivity();
        if (crbAcInfo == null) {
            msg.setEndTime(0);
        }else {
            msg.setEndTime(crbAcInfo.getBeginShowTime() * 1000);
        }
        return msg;
    }

    //陈宫加入宴会，结算奖励
    public static String joinCrossBanquet(GamePlayer player,String banquetId,int giftId,int pos){
        UserCrossBanquetData userCrossBanquetData = userCrossBanquetDataMap.get(banquetId);
        BanquetGiftInfo banquetGiftInfo = BanquetConfigMgr.getBanquetGiftInfo(userCrossBanquetData.getType(),giftId);
        BanquetInfo banquetInfo = BanquetConfigMgr.getBanquetInfo(userCrossBanquetData.getType());
        int titleAdd = 0;
        if(banquetInfo.isTitleAdd()){
            //随礼的奖励值加上头衔加成千分比
            TitleInfo titleInfo = TitleMgr.getTitleInfo(player.getTitleId());
            //头衔加成
            titleAdd = titleInfo.getBanquetEffect();
        }
        Property joinScore = PropertyHelper.parseStringToProperty(banquetGiftInfo.getJoinScore());
        long popularity = joinScore.getCountByGoodsId(GameConfig.BANQUET_POPULARITY).longValue();
        long integral = joinScore.getCountByGoodsId(GameConfig.BANQUET_INTEGRAL).longValue();
        BigDecimal popularityBigDecimal = BigDecimal.valueOf(popularity).multiply((BigDecimal.valueOf(1000+titleAdd))).divide(BigDecimal.valueOf(1000),3,BigDecimal.ROUND_UP);
        integral = BigDecimal.valueOf(integral).multiply((BigDecimal.valueOf(1000+titleAdd))).divide(BigDecimal.valueOf(1000),0,BigDecimal.ROUND_UP).longValue();
        //门客技能加成
        int skillAddition = BanquetMgr.getBanquetJoinSkillAddition(player);
        popularity = popularityBigDecimal.
                multiply(BigDecimal.valueOf(1000).add(BigDecimal.valueOf(skillAddition))).
                divide(BigDecimal.valueOf(1000),0,BigDecimal.ROUND_UP).longValue();

        CrossBanquetMgr.addBanquetPopularityAndIntegral(player,popularity,integral,eLogMoneyType.BanquetJoinReward.getValue());

        String reward = "";
        if(!"0".equals(banquetGiftInfo.getJoinConsume())){
            player.getModule(CurrencyModule.class).removeCurrency(PropertyHelper.parseStringToProperty(banquetGiftInfo.getJoinConsume()), eLogMoneyType.Banquet, eLogMoneyType.BanquetUserCrossJoinConsume);
        }
        if(!"0".equals(banquetGiftInfo.getJoinReward())){
            if(banquetGiftInfo.getType1() == eBanquetType.CrossMogulBirthdayBanquet.getValue()){
                reward = banquetGiftInfo.getJoinReward();
                player.getModule(CurrencyModule.class).addCurrency(reward,eLogMoneyType.Banquet,eLogMoneyType.BanquetJoinReward);
            }else {
                reward = BanquetConfigMgr.getJoinReward(pos,giftId);
                Property joinReward = PropertyHelper.parseStringToProperty(reward);
                player.getModule(CurrencyModule.class).addCurrency(joinReward,eLogMoneyType.Banquet,eLogMoneyType.BanquetJoinReward);
            }
        }

        return reward;
    }

    public static void sendLuckUserReward(String banquetId,long userId){
        UserCrossBanquetData userCrossBanquetData = CrossBanquetMgr.getBanquet(banquetId);
        BanquetInfo banquetInfo = BanquetConfigMgr.getBanquetInfo(userCrossBanquetData.getType());
        if(!"0".equals(banquetInfo.getLockReward())){
            UserInfo userInfo = UserMgr.getUserInfo(userId);
            String mailTitle = MultipleLanguageMgr.getContent(MailManager.BANQUET_LUCK_USER_TITLE, userInfo.getLanguage());
            String banquetName = MultipleLanguageMgr.getContent(banquetInfo.getName(), userInfo.getLanguage());
            String mailContent = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.BANQUET_LUCK_USER_CONTENT, userInfo.getLanguage()),
                    userCrossBanquetData.getUserBaseInfo().getNickName(),banquetName);
            MailManager.sendMail(userId, eMailType.SYSTEM.getValue(), banquetInfo.getLockReward(), mailContent, mailTitle);
        }
    }

    //刚进宴会的时候分批同步人数
    public static boolean syncBanquetMember(GamePlayer player,UserCrossBanquetData banquetData,Map<Long, CrossBanquetMember> crossBanquetMemberMap){
        if(banquetData.isSceneUser(player.getUserId())){
            BanquetProto.BanquetMemberSync.Builder msg = BanquetPb.parseBanquetMemberSyncResp(banquetData,crossBanquetMemberMap,banquetData.getUserCount());
            player.sendPacket(Protocol.U_BANQUET_CROSS_MEMBER_SYNC, msg);
            return true;
        }
        return false;
    }

    public static void syncBanquetMember(CrossBanquetProto.SyncCrossBanquetMemberTemp temp){
        CrossBanquetMember member = new CrossBanquetMember();
        member.setBanquetId(temp.getBanquetId());
        member.setGiftId(temp.getGiftId());
        member.setIntegral(temp.getIntegral());
        member.setPopularity(temp.getPopularity());
        member.setUserId(temp.getUserId());
        member.setPos(temp.getPos());
        member.setRobot(temp.getRobot());
        member.setRobotProcessId(temp.getRobotProcessId());
        member.setRobotId(temp.getRobotId());
        member.setUserBaseInfo(PlayerBasePb.parseBaseUserInfo(temp.getUserBaseInfo()));
        member.setJoinTime(temp.getJoinTime());

        // 设置userBaseInfo到缓存内
        userBaseInfoMap.put(member.getUserId(), member.getUserBaseInfo());

        //有可能参加人数的同步先到了
        if(!crossBanquetMemberMap.containsKey(temp.getBanquetId())){
            crossBanquetMemberMap.put(temp.getBanquetId(),new ConcurrentHashMap<>());
        }
        crossBanquetMemberMap.get(temp.getBanquetId()).put(member.getUserId(),member);

        UserCrossBanquetData banquetData = userCrossBanquetDataMap.get(temp.getBanquetId());
        //防止客户端显示的不实时
        if(banquetData.getPopularity() < temp.getAllPopularity()){
            banquetData.setPopularity(temp.getAllPopularity());
        }
        if(banquetData.getIntegral() < temp.getAllIntegral()){
            banquetData.setIntegral(temp.getAllIntegral());
        }
        if(banquetData.getUserCount() < crossBanquetMemberMap.get(temp.getBanquetId()).size()){
            banquetData.setUserCount(crossBanquetMemberMap.get(temp.getBanquetId()).size());
        }
     //   syncBanquetMemberClient(banquetData,member);

    }

    //用户进入场景
    public static int addBanquetScene(long userId,String banquetId){
        Object lockObject = getLockValue(banquetId);
        if(lockObject == null){
            return GameErrorCode.E_GAME_ERROR;
        }
        synchronized (lockObject){
            userCrossBanquetDataMap.get(banquetId).addSceneUser(userId);
        }
        return 0;
    }

    //用户移除场景
    public static int removeAllBanquetScene(long userId){
        for(String banquetId : userCrossBanquetDataMap.keySet()){
            if(!isBanquetOver(banquetId)){
                Object lockObject = lockMap.get(banquetId);
                if(lockObject != null){
                    synchronized (lockObject){
                        userCrossBanquetDataMap.get(banquetId).removeSceneUser(userId);
                    }
                }
            }
        }
        return 0;
    }

    public static void syncBanquetMemberClient(UserCrossBanquetData banquetData,CrossBanquetMember crossBanquetMember){
        BanquetProto.BanquetMemberSync.Builder msg = BanquetPb.parseBanquetMemberSyncResp(banquetData,crossBanquetMember,banquetData.getUserCount());
        for(long userId : banquetData.getSceneBanquetUser()){
            GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
            if(player != null && player.getState() == PlayerState.ONLINE){
                Long pingTime = player.getLastPingTime();
                Long nowTime = System.currentTimeMillis();
                if(nowTime - pingTime < 5*1000){//ping小于5秒才同步
                    player.sendPacket(Protocol.U_BANQUET_CROSS_MEMBER_SYNC, msg);
                    continue;
                }
            }
            removeAllBanquetScene(userId);
        }

        GamePlayer player = GamePlayerMgr.getOnlinePlayer(banquetData.getUserId());
        if(player != null){
            syncSelfCrossBanquet(player,banquetData);
        }

        popRewardSync(banquetData);
    }

    public static UserCrossBanquetData getBanquet(String banquetId) {
        return userCrossBanquetDataMap.get(banquetId);
    }

    //获得参加宴会的用户，分页大小，第几页
    public static Map<Long,CrossBanquetMember> getBanquetMemberMap(String banquetId,int groupNum,int groupId){
        List<CrossBanquetMember> memberList = new ArrayList<>();
        if(!isBanquetOver(banquetId)){
            Map<Long, CrossBanquetMember> memberMap = crossBanquetMemberMap.get(banquetId);
            if (memberMap == null) {
                getLogger().info("banquetMemberMap is  null, id : {}",banquetId);
            }
            if (memberMap != null) {
                memberList = new ArrayList<>(memberMap.values());
            }
        }
        Map<Long,CrossBanquetMember> groupMemberMap = new ConcurrentHashMap<>();
        memberList.sort(new MemberSort());
        if(groupNum <= 0){
            for(CrossBanquetMember member : memberList){
                groupMemberMap.put(member.getUserId(),member);
            }
        }else{
            int startIndex = groupNum*(groupId - 1);
            for(int i = 0;i<groupNum;i++){
                if(memberList.size() > startIndex+i){
                    CrossBanquetMember member = memberList.get(startIndex+i);
                    groupMemberMap.put(member.getUserId(),member);
                }
            }
        }
        return groupMemberMap;
    }

    //从小到大按照座位排序
    static class MemberSort implements Comparator<CrossBanquetMember> {
        @Override
        public int compare(CrossBanquetMember o1, CrossBanquetMember o2) {
            if (o1.getPos() == o2.getPos()) {
                return 0;
            }
            if (o1.getPos() >= o2.getPos()) {
                return 1;
            }
            return -1;
        }
    }

    public static void syncSelfCrossBanquet(GamePlayer player,UserCrossBanquetData nowBanquet){
        List<UserCrossBanquetData> banquetList = new ArrayList<>(userCrossBanquetDataMap.values());
        List<UserCrossBanquetData> selfBanquetList = new ArrayList<>();
        for(UserCrossBanquetData info :banquetList){
            //最后一个人参加就结束的也要同步
            if(nowBanquet != null && nowBanquet.getBanquetId().equals(info.getBanquetId()) && BanquetMgr.isBanquetOver(info.getBanquetId())){
                selfBanquetList.add(info);
            }
            if(!isBanquetOver(info.getBanquetId()) && info.getUserId() == player.getUserId()){
                selfBanquetList.add(info);
            }
        }
        player.sendPacket(Protocol.U_BANQUET_CROSS_SELF_SYNC, BanquetPb.parseSyncSelfCrossBanquet(player,selfBanquetList));
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    public static void removeOverTimeBanquet(){
        for(UserCrossBanquetData info : userCrossBanquetDataMap.values()){
            //大于3小时的移除掉的结束活动(时间到了且已经领奖了)
            if(System.currentTimeMillis() - info.getOverTime() > 3*60*60*1000 && info.getStatus() == 1 && info.getOp() == DataStatus.None && info.isSendReward()){
                userCrossBanquetDataMap.remove(info.getBanquetId());
                crossBanquetMemberMap.remove(info.getBanquetId());
            }
            //大于十分钟没有开启成功的移除掉
            if(System.currentTimeMillis() - info.getOpenTime() > 10*60*1000 && info.getStatus() == 0){
                userCrossBanquetDataMap.remove(info.getBanquetId());
                crossBanquetMemberMap.remove(info.getBanquetId());
            }
        }
    }

    //预开没有成功的，再次向跨服发起开启消息
    public static void reStartBanquet(){
        for(UserCrossBanquetData info : userCrossBanquetDataMap.values()){
            //预开启成功但是还没开启宴会
            if(info.getStatus() == 0){
                CrossBanquetProto.OpenCrossBanquetReq.Builder msg = CrossBanquetProto.OpenCrossBanquetReq.newBuilder();
                msg.setBanquetId(info.getBanquetId());
                msg.setAutoOpen(info.getAutoOpen() == 1);

                GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(info.getUserId());
                if (onlinePlayer != null) {
                    TitleInfo titleInfo = TitleMgr.getTitleInfo(onlinePlayer.getTitleId());
                    //头衔加成
                    int titleAdd = titleInfo.getBanquetEffect();
                    //门客技能加成
                    int skillAdd = BanquetMgr.getBanquetJoinSkillAddition(onlinePlayer);
                    msg.setTitleAdd(titleAdd);
                    msg.setPatronsSkillAdd(skillAdd);
                    msg.setPlayerBaseData(PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.getUserBaseInfo(onlinePlayer.getUserId(), GameServer.getInstance().getServerId())));
                }
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_OPEN_BANQUET, msg);
                GamePlayerMgr.sendPacket(info.getUserId(), pbMsg);
            }
        }
    }

    public boolean save() {
        reStartBanquet();
        removeOverTimeBanquet();
        List<UserCrossBanquetData> banquetList = new ArrayList<>(userCrossBanquetDataMap.values());
        for(UserCrossBanquetData info : banquetList){
            if(info.getOp() == DataStatus.Insert){
                UserBanquetBussiness.addUserCrossBanquet(info);
            }else if(info.getOp() == DataStatus.Update){
                UserBanquetBussiness.updateUserCrossBanquet(info);
            }
        }
        for (List<GoodBanquetFinishReceiveData> list : finishGoodBanquetMap.values()){
            List<GoodBanquetFinishReceiveData> tempList = null;
            synchronized (list){
                tempList = new ArrayList<>(list);
            }
            for (GoodBanquetFinishReceiveData item : tempList){
                if(item.isUpdateOption()){
                    DaoHelper.getGoodBanquetFinishReceiveDataDaoImpl().update(item);
                }else if(item.isInsertOption()){
                    DaoHelper.getGoodBanquetFinishReceiveDataDaoImpl().add(item);
                }
            }
        }

        // 全部userBaseInfo设置成缓存内的userBaseInfo
        for (Map<Long, CrossBanquetMember> map : crossBanquetMemberMap.values()) {
            for (CrossBanquetMember member : map.values()) {
                UserBaseInfo tempUserBaseInfo = userBaseInfoMap.get(member.getUserId());
                if (tempUserBaseInfo != null) {
                    member.setUserBaseInfo(tempUserBaseInfo);
                }
            }
        }

        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean reloadData() {
        if (threadTaskManger == null) {
            threadTaskManger = new ThreadTaskManger(2, "WorldMessageTaskManger");
        }
        userCrossBanquetDataMap = UserBanquetBussiness.getRunningUserCrossBanquetMap();
        initLockMap();
        initUserBanquetMember();
        initGoodBanquet();
        return true;
    }

    private static void initUserBanquetMember(){

        int channelId = ServerListMgr.getChannelId(GameServer.getInstance().getServerId());
        CrossServerInfoDaoImpl crossServerInfoDaoImpl = new CrossServerInfoDaoImpl();
        CrossServerInfo crossServerInfo = crossServerInfoDaoImpl.getCrossServerInfo(channelId, crossServerInfoDaoImpl.getCrossRankServerId(GameServer.getInstance().getServerId()).getCrossBanquetServerId());
        DbInfo dbInfo = crossServerInfo.getDbInfos().get(0);
        String crossDbParam = dbInfo.getIp() + "|" +dbInfo.getPort() + "|" + dbInfo.getDbName() + "|" + dbInfo.getUserName() + "|" + dbInfo.getPassword();

        for(UserCrossBanquetData data : userCrossBanquetDataMap.values()){
            if(!BanquetConfigMgr.isServerNormalBanquet(data.getType()) && isBanquetOver(data.getBanquetId())){
                continue;
            }
            Map<Long, CrossBanquetMember> userMap = new CrossBanquetMemberNotPoolDaoImpl(crossDbParam).getCrossBanquetMemberMap(data.getBanquetId());
            crossBanquetMemberMap.put(data.getBanquetId(),userMap);

            for (CrossBanquetMember member : userMap.values()) {
                // 缓存userBaseInfo
                if (userBaseInfoMap.containsKey(member.getUserId())) {
                    if (userBaseInfoMap.get(member.getUserId()).getLastLoginTime() < member.getUserBaseInfo().getLastLoginTime()) {
                        // 写入登录时间最新的那个记录
                        userBaseInfoMap.put(member.getUserId(), member.getUserBaseInfo());
                    }
                } else {
                    userBaseInfoMap.put(member.getUserId(), member.getUserBaseInfo());
                }
            }
        }

        // 全部userBaseInfo设置成缓存内的userBaseInfo
        for (Map<Long, CrossBanquetMember> map : crossBanquetMemberMap.values()) {
            for (CrossBanquetMember member : map.values()) {
                UserBaseInfo tempUserBaseInfo = userBaseInfoMap.get(member.getUserId());
                if (tempUserBaseInfo != null) {
                    member.setUserBaseInfo(tempUserBaseInfo);
                }
            }
        }

    }

    private static void initLockMap() {
        lockMap = new HashMap<>();
        for (Map.Entry<String, UserCrossBanquetData> userCrossBanquetDataInfo : userCrossBanquetDataMap.entrySet()) {
            lockMap.put(userCrossBanquetDataInfo.getKey(), new Object());
        }
    }

    private static void initGoodBanquet(){
        finishGoodBanquetMap = DaoHelper.getGoodBanquetFinishReceiveDataDaoImpl().getGoodBanquetFinishReceiveDataMap();
    }

    private static void addLockValue(String banquetId){
        if(!lockMap.containsKey(banquetId)){
            lockMap.put(banquetId,new Object());
        }
    }

    private static Object getLockValue(String banquetId){
        if(lockMap.containsKey(banquetId)){
            return lockMap.get(banquetId);
        }
        return null;
    }

    public static Set<Long> getInSystemUserSet() {
        return inSystemUserSet;
    }

    public static void removeActivity(GamePlayer player){
        CrossBanquetMgr.getInSystemUserSet().remove(player.getUserId());
    }

    public static List<CrossBanquetProto.GoodBanquetSettlementReward> receiveGoodBanquetSettlementReward(GamePlayer player){
        List<CrossBanquetProto.GoodBanquetSettlementReward> rewardList = new ArrayList<>();
        List<GoodBanquetFinishReceiveData> list = CrossBanquetMgr.getUserFinishGoodBanquetList(player.getUserId(),false);
        if(list != null && list.size() > 0){
            synchronized (list){
                for (GoodBanquetFinishReceiveData item : list){
                    if(item.getIsReceive()){
                        continue;
                    }
                    CrossBanquetProto.GoodBanquetSettlementReward.Builder reward = CrossBanquetProto.GoodBanquetSettlementReward.newBuilder();
                    // 加奖励
                    BanquetInfo banquetInfo = BanquetConfigMgr.getBanquetInfo(item.getType());
                    if (!"0".equals(banquetInfo.getEndReward())) {
                        String endRewardStr = BanquetConfigMgr.getEndReward(item.getNum(), item.getType());
                        Property endReward = PropertyHelper.parseStringToProperty(endRewardStr);
                        int popularity = endReward.getCountByGoodsId(GameConfig.BANQUET_POPULARITY).intValue();
                        int integral = endReward.getCountByGoodsId(GameConfig.BANQUET_INTEGRAL).intValue();
                        endReward.removeProperty(GameConfig.BANQUET_POPULARITY, BigInteger.valueOf(popularity));


                        reward.setReward(PropertyHelper.parsePropertyToString(endReward));
                        reward.setPopularity(popularity);

                        endReward.removeProperty(GameConfig.BANQUET_INTEGRAL, BigInteger.valueOf(integral));
                        player.getModule(CurrencyModule.class).addCurrency(endReward, eLogMoneyType.Banquet,eLogMoneyType.BanquetOpenGoodBanquetSettlementReward);
                        addBanquetPopularityAndIntegral(player,popularity,integral,eLogMoneyType.BanquetJoinReward.getValue());
                    }
                    item.setIsReceive(true);
                    reward.setNum(item.getNum());
                    reward.setType(item.getType());
                    reward.setEndTime(item.getEndTime());

                    rewardList.add(reward.build());
                }
            }
        }
        return rewardList;
    }


    public static List<GoodBanquetFinishReceiveData> getUserFinishGoodBanquetList(long userId,boolean newIfNull) {
        List<GoodBanquetFinishReceiveData> list = finishGoodBanquetMap.get(userId);
        if(list == null && newIfNull){
            synchronized (finishGoodBanquetMap){
                if(!finishGoodBanquetMap.containsKey(userId)){
                    list = new ArrayList<>();
                    finishGoodBanquetMap.put(userId, list);
                }
            }
        }
        return list;
    }

    /**
     * 加宴会积分 人气
     * @param player
     * @param popularity
     * @param integral
     */
    public static void addBanquetPopularityAndIntegral(GamePlayer player,long popularity, long integral,int son){
        long oldIntegral = player.getModule(AttributeModule.class).getAttribute(ePlayerAttrType.BanquetIntegral);
        player.getModule(AttributeModule.class).addAttribute(ePlayerAttrType.BanquetPopularity, popularity);
        player.getModule(AttributeModule.class).addAttribute(ePlayerAttrType.BanquetIntegral, integral);
        //小面任务
        player.getModule(XiaoMianModule.class).addBanquetScore(integral);

        player.notifyListener(eGamePlayerEventType.BanquetIntegral.getValue(), integral);
        player.notifyListener(eGamePlayerEventType.BanquetTotalScoreRise.getValue(),integral);
        player.notifyListener(eGamePlayerEventType.UnionBanquetIntegral.getValue(), new UnionActivityTaskArgs(UnionActivityTaskArgs.TYPE_ADD_VALUE, integral, player.getUserInfo().getUnionUid()));
        player.notifyListener(eGamePlayerEventType.BanquetPopularityRank.getValue(), popularity);
        //宴会人气榜单
        RankMgr.changeUserRank(eBigRankType.Normal.getValue(), player.getUserId(), BigInteger.valueOf(player.getModule(AttributeModule.class).getAttribute(ePlayerAttrType.BanquetPopularity)), eRankType.Banquet.getValue(), "");
        if(integral != 0){
            AutoLogMgr.add(new LogBanquetIntegral(player.getUserId(), oldIntegral, oldIntegral + integral, integral, eLogMoneyType.Banquet.getValue(), son));
        }
    }

    /**
     * 获取能进入百福宴的活动 (beginTime,endShowTime)
     */
    public static ActivityInfo getEnterGoodBanquetActivityInfo(){
        long nowTime = System.currentTimeMillis() / 1000;
        for (ActivityInfo activityInfo : NormalActivityMgr.getRankActivityInfoList()) {
            if (activityInfo.getType() == eActivityType.CrossRankActivity.getValue() && activityInfo.getChildType() == 5) {
                if (nowTime > activityInfo.getBeginTime() && nowTime < activityInfo.getEndShowTime()) {
                    return activityInfo;
                }
            }
        }
        return null;
    }

    /**
     * 是否能进入百福宴的活动 (beginTime,endShowTime)
     */
    public static boolean isEnterGoodBanquet(int activityId){
        long nowTime = System.currentTimeMillis() / 1000;
        ActivityInfo activityInfo = NormalActivityMgr.getActivityInfo(activityId);
        if (activityInfo != null && activityInfo.getType() == eActivityType.CrossRankActivity.getValue() && activityInfo.getChildType() == 5) {
            if (nowTime > activityInfo.getBeginTime() && nowTime < activityInfo.getEndShowTime()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 是否能开百福宴的活动 (beginTime,endTime) 两个服以上才让开宴会
     */
    public static boolean canOpenGoodBanquet(int activityId){
        long nowTime = System.currentTimeMillis() / 1000;
        ActivityInfo activityInfo = NormalActivityMgr.getActivityInfo(activityId);
        if (activityInfo != null && activityInfo.getType() == eActivityType.CrossRankActivity.getValue() && activityInfo.getChildType() == 5) {
            if (nowTime > activityInfo.getBeginTime() && nowTime < activityInfo.getEndTime()) {
                return true;
            }
        }
        return false;
    }


    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(50);
        Map<String, Integer> dataMAp = new ConcurrentHashMap<>();
        for (int i = 0; i < 10000000; i++) {
            service.execute(() -> {
                String s = UUID.randomUUID().toString();
                dataMAp.put(s, 1);

            });
        }
       service.shutdown();
        while (!service.isTerminated()) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println(dataMAp.size());
    }
}
